import React from "react";
import {
  Row,
  Col,
  Form,
  Input,
  Button,
  DatePicker,
  Select,
  Radio /* , Dropdown */,
} from "antd";
import styles from "./AdvancedFilter.less";

const { RangePicker } = DatePicker;
const { Option } = Select;

const statusConfig = [
  { label: "正常", value: "NORMAL" },
  { label: "预警", value: "WARNING" },
  { label: "超时", value: "TIMEOUT" },
  { label: "终止", value: "END" },
  { label: "撤办", value: "RECALL" },
  { label: "暂停", value: "PAUSE" },
  { label: "错误", value: "ERROR" },
];

@Form.create()
class AdvancedFilter extends React.Component {
  state = {
    totalWay: "byDay",
    selectedYear: undefined,
  };

  formItemLayout = {
    labelCol: { span: 5 },
    wrapperCol: { span: 19 },
  };

  componentDidMount() {
    const { getFormThis } = this.props;
    if (getFormThis) getFormThis(this, "advancedFilter");
  }

  handleReset = () => {
    const { form, renderType } = this.props;
    if (renderType === "instanceTotal" || renderType === "taskTotal") {
      this.setState({
        totalWay: "byDay",
        selectedYear: undefined,
      });
    }
    form.resetFields();
  };

  handleSubmit = (e) => {
    if (e && e.preventDefault) e.preventDefault();
    const { form, handleParamsChange } = this.props;
    form.validateFields((err, values) => {
      if (err) {
        return;
      }
      const { datatime } = values;
      const param = { ...values };
      delete param.datatime;
      if (datatime && datatime.length > 0) {
        param.startTime = datatime[0].format("YYYY-MM-DD HH:mm:ss");
        param.endTime = datatime[1].format("YYYY-MM-DD HH:mm:ss");

        param.startDate = datatime[0].format("YYYY-MM-DD");
        param.endDate = datatime[1].format("YYYY-MM-DD");
      } else {
        param.startTime = "";
        param.endTime = "";
        param.startDate = "";
        param.endDate = "";
      }
      if (values.applyUserNames) {
        param.applyUserNames = values.applyUserNames.split(/,|，/);
      }
      if (handleParamsChange) handleParamsChange(param);
    });
  };

  handleSearch = () => {
    const { onSearch } = this.props;
    if (onSearch instanceof Function) onSearch();
  };

  handleTaskTotalWay = (e) => {
    this.setState({
      totalWay: e.target.value,
      selectedYear: new Date().getFullYear(),
    });
  };

  getYear = () => {
    const nowYear = new Date().getFullYear();
    const year = [];
    for (let i = nowYear; i > nowYear - 5; i -= 1) {
      year.push(
        <Select.Option key={i} value={i} className="year-item">
          {`${i}年`}
        </Select.Option>,
      );
    }
    return year;
  };

  getMonth = () => {
    const month = [];
    for (let i = 1; i < 13; i += 1) {
      month.push(
        <Select.Option key={i} value={i} className="year-item">
          {`${i}月`}
        </Select.Option>,
      );
    }
    return month;
  };

  renderFlowFilter() {
    const { form, visible } = this.props;
    const { getFieldDecorator } = form;

    return (
      <div className={`filter__box ${!visible ? "box__hidden" : ""}`}>
        <Form layout="horizontal">
          <Row
            className={`filter_form_box ${styles.filter_b_box} ${styles.lbl_w}`}
          >
            <Col span={8}>
              <Form.Item label="流程编码" {...this.formItemLayout}>
                {getFieldDecorator(
                  "modelKey",
                  {},
                )(
                  <Input
                    placeholder="请输入流程编码"
                    className="input__search"
                  />,
                )}
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item label="流程实例ID" {...this.formItemLayout}>
                {getFieldDecorator(
                  "processInstanceId",
                  {},
                )(
                  <Input
                    placeholder="请输入流程编码"
                    className="input__search"
                  />,
                )}
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item label="发起时间" {...this.formItemLayout}>
                {getFieldDecorator("datatime", {
                  initialValue: "",
                })(
                  <RangePicker
                    format="YYYY-MM-DD HH:mm:ss"
                    className="input__search"
                    placeholder={["开始时间", "结束时间"]}
                    showTime
                    style={{ width: "100%" }}
                  />,
                )}
              </Form.Item>
            </Col>
          </Row>
          <Row
            className={`filter_form_box ${styles.filter_b_box} ${styles.lbl_w}`}
          >
            <Col span={8}>
              <Form.Item label="实例状态" {...this.formItemLayout}>
                {getFieldDecorator("status", {
                  // initialValue: '',
                })(
                  <Select placeholder="请选择状态">
                    {statusConfig.map(({ label, value }) => (
                      <Option key={value} value={value}>
                        {label}
                      </Option>
                    ))}
                  </Select>,
                )}
              </Form.Item>
            </Col>
            <Col span={16}>
              <div className="filter_buttons">
                <Button type="primary" size="small" onClick={this.handleSearch}>
                  查询
                </Button>
                <Button size="small" onClick={this.handleReset}>
                  重置
                </Button>
              </div>
            </Col>
          </Row>
        </Form>
      </div>
    );
  }

  renderTaskFilter() {
    const { form, visible } = this.props;
    const { getFieldDecorator } = form;

    return (
      <div className={`filter__box ${!visible ? "box__hidden" : ""}`}>
        <Form layout="horizontal">
          <Row
            className={`filter_form_box ${styles.filter_b_box} ${styles.lbl_w}`}
          >
            <Col span={8}>
              <Form.Item label="流程编码" {...this.formItemLayout}>
                {getFieldDecorator(
                  "modelKey",
                  {},
                )(
                  <Input
                    placeholder="请输入流程编码"
                    className="input__search"
                  />,
                )}
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item label="流程名称" {...this.formItemLayout}>
                {getFieldDecorator(
                  "modelName",
                  {},
                )(
                  <Input
                    placeholder="请输入流程名称"
                    className="input__search"
                  />,
                )}
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item label="任务编码" {...this.formItemLayout}>
                {getFieldDecorator(
                  "activityId",
                  {},
                )(
                  <Input
                    placeholder="请输入任务编码"
                    className="input__search"
                  />,
                )}
              </Form.Item>
            </Col>
          </Row>
          <Row
            className={`filter_form_box ${styles.filter_b_box} ${styles.lbl_w}`}
          >
            <Col span={8}>
              <Form.Item label="任务创建时间" {...this.formItemLayout}>
                {getFieldDecorator(
                  "datatime",
                  {},
                )(
                  <RangePicker
                    format="YYYY-MM-DD HH:mm:ss"
                    className="input__search"
                    placeholder={["开始时间", "结束时间"]}
                    showTime
                    style={{ width: "100%" }}
                  />,
                )}
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item label="任务状态" {...this.formItemLayout}>
                {getFieldDecorator("status", {
                  // initialValue: '',
                })(
                  <Select placeholder="请选择状态">
                    {statusConfig.map(({ label, value }) => (
                      <Option key={value} value={value}>
                        {label}
                      </Option>
                    ))}
                  </Select>,
                )}
              </Form.Item>
            </Col>
            <Col span={8}>
              <div className="filter_buttons">
                <Button type="primary" size="small" onClick={this.handleSearch}>
                  查询
                </Button>
                <Button size="small" onClick={this.handleReset}>
                  重置
                </Button>
              </div>
            </Col>
          </Row>
        </Form>
      </div>
    );
  }

  // 流程任务统计
  renderTaskTotalFilter() {
    const { form, visible } = this.props;
    const { getFieldDecorator } = form;
    const { totalWay, selectedYear } = this.state;
    return (
      <div className={`filter__box ${!visible ? "box__hidden" : ""}`}>
        <Form layout="horizontal">
          <Row
            className={`filter_form_box ${styles.filter_b_box} ${styles.lbl_w}`}
          >
            <Col span={7}>
              <Form.Item label="统计方式" {...this.formItemLayout}>
                {getFieldDecorator("summaryType", {
                  initialValue: "byDay",
                })(
                  <Radio.Group onChange={this.handleTaskTotalWay}>
                    <Radio value="byDay">按日</Radio>
                    <Radio value="byMonth">按月</Radio>
                  </Radio.Group>,
                )}
              </Form.Item>
            </Col>
            <Col
              span={12}
              style={{ display: totalWay === "byDay" ? "block" : "none" }}
            >
              <Form.Item label="发起日期" {...this.formItemLayout}>
                {getFieldDecorator(
                  "datatime",
                  {},
                )(
                  <RangePicker
                    format="YYYY-MM-DD"
                    className="input__search"
                    placeholder={["开始时间", "结束时间"]}
                    style={{ width: "100%" }}
                  />,
                )}
              </Form.Item>
            </Col>
            <Col
              span={6}
              style={{ display: totalWay === "byMonth" ? "block" : "none" }}
            >
              <Form.Item label="发起年份" {...this.formItemLayout}>
                {getFieldDecorator("year", {
                  initialValue: selectedYear,
                })(<Select placeholder="请选择年份">{this.getYear()}</Select>)}
              </Form.Item>
            </Col>
            <Col
              span={6}
              style={{ display: totalWay === "byMonth" ? "block" : "none" }}
            >
              <Form.Item label="发起月份" {...this.formItemLayout}>
                {getFieldDecorator(
                  "months",
                  {},
                )(
                  <Select mode="multiple" placeholder="请选择月份">
                    {this.getMonth()}
                  </Select>,
                )}
              </Form.Item>
            </Col>
            <Col span={5}>
              <div className="filter_buttons">
                <Button type="primary" size="small" onClick={this.handleSearch}>
                  查询
                </Button>
                <Button size="small" onClick={this.handleReset}>
                  重置
                </Button>
              </div>
            </Col>
          </Row>
        </Form>
      </div>
    );
  }

  renderItem = (renderType) => {
    // renderType: flow 流程 task 任务 taskTotal 任务统计 instanceTotal 实例统计
    switch (renderType) {
      case "flow":
        return this.renderFlowFilter();
      case "task":
        return this.renderTaskFilter();
      case "taskTotal":
        return this.renderTaskTotalFilter();
      case "instanceTotal":
        return this.renderTaskTotalFilter();
      default:
        return this.renderFlowFilter();
    }
  };

  render() {
    // renderType: flow 流程 task 任务
    const { renderType = "flow" } = this.props;
    return <>{this.renderItem(renderType)}</>;
  }
}

export default AdvancedFilter;
